#include "barcode_printer.h"
#include <cstdlib>
#include <map>
#include <vector>
#include <sstream>

// 字符串分割函数
const std::vector<std::string> split(const std::string& str, const std::string& pattern) {
    std::vector<std::string> result;
    std::string::size_type begin, end;

    end = str.find(pattern);
    begin = 0;

    while (end != std::string::npos) {
        if (end - begin != 0) {
            result.push_back(str.substr(begin, end - begin));
        }
        begin = end + pattern.size();
        end = str.find(pattern, begin);
    }

    if (begin != str.length()) {
        result.push_back(str.substr(begin));
    }
    return result;
}

// 简单的JSON解析函数（仅用于解析打印机信息）
bool parsePrinterJson(const std::string& jsonStr, std::map<std::string, int>& printers) {
    // 简单的JSON解析，只处理 {"printerName":"port"} 格式
    if (jsonStr.empty() || jsonStr[0] != '{' || jsonStr.back() != '}') {
        return false;
    }
    
    std::string content = jsonStr.substr(1, jsonStr.length() - 2); // 去掉大括号
    size_t colonPos = content.find(':');
    if (colonPos == std::string::npos) {
        return false;
    }
    
    std::string name = content.substr(0, colonPos);
    std::string port = content.substr(colonPos + 1);
    
    // 去掉引号
    if (name.length() >= 2 && name[0] == '"' && name.back() == '"') {
        name = name.substr(1, name.length() - 2);
    }
    if (port.length() >= 2 && port[0] == '"' && port.back() == '"') {
        port = port.substr(1, port.length() - 2);
    }
    
    std::string printerInfo = name + ":" + port;
    printers[printerInfo] = 1; // 1表示USB设备
    return true;
}

int main(int argc, char* argv[]) {
    // 创建模拟的打印信息结构体
    PrintInfo printInfo;
    printInfo.paperType = 70277;  // 50*30mm纸张
    printInfo.printType = 2;      // 带文本信息模式（可以改为1测试单条码模式）
    strcpy_s(printInfo.code, "1250025002500010002507203240000500000002");  // 40位模拟条码
    
    strcpy_s(printInfo.info[0], "Product Name");
    strcpy_s(printInfo.info[1], "Price: $99.00");
    strcpy_s(printInfo.info[2], "Stock: 100");
    
    BarcodePrinter printer;
    
    std::cout << "Initializing printer SDK..." << std::endl;
    if (!printer.initialize()) {
        std::cerr << "Error: SDK initialization failed" << std::endl;
        return 1;
    }
    
    // 查找并连接打印机
    std::cout << "Searching for printers..." << std::endl;
    std::map<std::string, int> printers; // 打印机列表，第二个参数为标志位（1-usb, 2-wifi）
    
    // 查找USB打印机
    char* printerList = Printer::getAllPrinters();
    if (printerList) {
        std::cout << "Found USB printer: " << printerList << std::endl;
        parsePrinterJson(std::string(printerList), printers);
        Printer::FreeBuffer(printerList);
    }
    
    // 查找WiFi打印机
    char* wifiPrinterList = Printer::scanWifiPrinter();
    if (wifiPrinterList) {
        std::cout << "Found WiFi printer: " << wifiPrinterList << std::endl;
        // 这里可以添加WiFi打印机解析逻辑
        Printer::FreeBuffer(wifiPrinterList);
    }
    
    if (printers.empty()) {
        std::cerr << "Error: No printer found" << std::endl;
        printer.cleanup();
        return 1;
    }
    
    // 选择第一个找到的打印机进行连接
    std::string selectedPrinter = printers.begin()->first;
    int printerType = printers.begin()->second;
    
    std::cout << "Selected printer: " << selectedPrinter << " (Type: " << (printerType == 1 ? "USB" : "WiFi") << ")" << std::endl;
    
    // 解析打印机信息
    std::vector<std::string> printerConf = split(selectedPrinter, ":");
    if (printerConf.size() != 2) {
        std::cerr << "Error: Invalid printer information format" << std::endl;
        printer.cleanup();
        return 1;
    }
    
    std::string printerName = printerConf[0];
    int port = std::stoi(printerConf[1]);
    
    std::cout << "Connecting to printer: " << printerName << " on port " << port << std::endl;
    
    bool connectSuccess = false;
    if (printerType == 1) {
        // USB设备
        connectSuccess = Printer::selectPrinter(const_cast<char*>(printerName.c_str()), port);
    } else if (printerType == 2) {
        // WiFi设备
        connectSuccess = Printer::connectWifiPrinter(const_cast<char*>(printerName.c_str()), port);
    }
    
    if (!connectSuccess) {
        std::cerr << "Error: Failed to connect to printer, error code: " << Printer::getLastPrinterError() << std::endl;
        printer.cleanup();
        return 1;
    }
    std::cout << "Printer connected successfully!" << std::endl;
    
    // 执行打印
    bool success = printer.printBarcode(printInfo);
    
    // 清理资源
    printer.cleanup();
    
    if (success) {
        std::cout << "Print task completed!" << std::endl;
        return 0;
    } else {
        std::cerr << "Print task failed!" << std::endl;
        return 1;
    }
}
